package MyThread;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: AliceMana
 * Date: 2023-01-12
 * Time: 16:13
 */
public class ThreadDemo28 {
    public static void main(String[] args) throws InterruptedException {
        // 基于 CAS 实现的原子类, 实现自增 自减的操作, 进行此类操作时不需要进行加锁, 是线程安全的
        AtomicInteger count  = new AtomicInteger();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                count.getAndIncrement(); // count++
                // count.incrementAndGet(); // ++count
                // count.getAndDecrement(); // count--
                // count.decrementAndGet(); // --count
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                count.getAndIncrement();
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count.get()); // 10000
    }

}
















